package com.leap.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.Interact;
import com.leap.entity.InteractComment;
import com.leap.mapper.InteractMapper;
import com.leap.service.InteractService;
import com.leap.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class InteractServiceImpl extends ServiceImpl<InteractMapper, Interact> implements InteractService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void getInteractListByAccountIdInMQL(Long accountId) {

        LambdaQueryWrapper<Interact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Interact::getAccountId, accountId);
        queryWrapper.orderByDesc(Interact::getCreateTime);
        List<Interact> list = this.list(queryWrapper);

        String key = Const.ACCOUNT_LIKE + accountId;

        if (!list.isEmpty()) {

            List<Long> articleIdList = list.stream().map(Interact::getArticleId).toList();
            redisTemplate.opsForList().rightPushAll(key, articleIdList);
            redisTemplate.expire(key, 7, TimeUnit.DAYS);
        }
    }

    @Override
    public void refreshInteractList(Long accountId) {

        String key = Const.ACCOUNT_LIKE + accountId;
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        this.getInteractListByAccountIdInMQL(accountId);

    }

    @Override
    public void deleteAllInteract(Long articleId) {
        String key = Const.ACCOUNT_LIKE + "*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        LambdaQueryWrapper<Interact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Interact::getArticleId, articleId);

        this.remove(queryWrapper);

    }

}
